﻿using System;
using System.IO;

namespace Lon.Server
{

    internal class CSMRtKglPackageProcess : DataProcessProvider
    {
        private NetNodeManager csmNodeManager = null;

        public CSMRtKglPackageProcess(NetNodeManager nodeManager)
        {
            this.csmNodeManager = nodeManager;
            
        }

        protected override void ProcessDataPackage(DataFrame pkgData)
        {
            if (pkgData.IsLonSelfFrame)
            {
                ProcessLonKglFrame(pkgData);
            }
            else
            {
                ProcessKglFrame(pkgData);
            }
        }
        private void ProcessKglFrame(DataFrame pkg)
        {
            NetNode csmNode = this.csmNodeManager.GetNode(pkg.SrcId);
            csmNode = new NetNode();
            csmNode.Id = pkg.SrcId;
            csmNode.Dbm = pkg.SrcDbm;
            csmNode.Ip = "";
            csmNode.Name = csmNode.Dbm;
            if (csmNode == null) return ;
            if (!csmNode.IsTJWX) return;
            MemoryStream ms = new MemoryStream(pkg.Buf);
            BinaryReader br = new BinaryReader(ms);
            ms.Seek(20, SeekOrigin.Begin);
            if (pkg.Buf.Length < 24) return; 
            uint kglTime = (uint)(pkg.Buf[20] + pkg.Buf[21] * 256 + pkg.Buf[22] * 256 * 256 + pkg.Buf[23] * 256 * 256);
            bool isChange = pkg.MinorDataType==0x81;
            DataStoreService.SaveKgl(pkg.SrcId, kglTime, pkg.MinorDataType, pkg.Buf);


            if (isChange)
            {
                csmNode.AllKglFrame = pkg;
            }
            else
            {
                csmNode.AllKglFrame = pkg;
            }
           
        }

        private void ProcessLonKglFrame(DataFrame pkg)
        {
            NetNode csmNode = this.csmNodeManager.GetNode(pkg.SrcId);
            if (csmNode == null) return;
            if (csmNode.IsTJWX) return;
            MemoryStream ms = new MemoryStream(pkg.Buf);
            BinaryReader br = new BinaryReader(ms);
            ms.Seek(20, SeekOrigin.Begin);
            if (pkg.Buf.Length < 24) return;
            uint kglTime = (uint)(pkg.Buf[20] + pkg.Buf[21] * 256 + pkg.Buf[22] * 256 * 256 + pkg.Buf[23] * 256 * 256);
            bool isChange = pkg.MinorDataType == 0x81;
            DataStoreService.SaveKgl(pkg.SrcId, kglTime, pkg.MinorDataType, pkg.Buf);
            if (isChange)
            {
                csmNode.AllKglFrame = pkg;
            }
            else
            {
                csmNode.AllKglFrame = pkg;
            }
             
           
       
        }
    }
}

